package com.wzw.springcloudgateway.config;

import com.wzw.springcloudgateway.filters.GlobalGatewayFilter;
import com.wzw.springcloudgateway.filters.PartialGatewayFilterFactory;
import com.wzw.springcloudgateway.predicates.TerminalRoutePredicateFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.cloud.gateway.config.conditional.ConditionalOnEnabledFilter;
import org.springframework.cloud.gateway.config.conditional.ConditionalOnEnabledPredicate;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;

/**
 * @author Wangzhiwen
 */
@Configuration
public class CustomerGatewayConfiguration {

    /**
     * 自定义的Predicate
     *
     * @return PathIncludeVarPredicate
     */
    @Bean
    @ConditionalOnEnabledPredicate
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public TerminalRoutePredicateFactory pathIncludeVarPredicate() {
        return new TerminalRoutePredicateFactory();
    }

    /**
     * 自定义的全局过滤器，一般用于鉴权与日志输出
     *
     * @return GlobalFilter
     */
    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public GlobalGatewayFilter globalGatewayFilter() {
        return new GlobalGatewayFilter();
    }

    /**
     * 自定义的非全局过滤器，一般用于某个具体路由的请求拦截
     *
     * @return AbstractGatewayFilterFactory
     */
    @Bean
    @ConditionalOnEnabledFilter
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public PartialGatewayFilterFactory partialGatewayFilter() {
        return new PartialGatewayFilterFactory();
    }

    /**
     * API构建RouteLocator的实现
     *
     * @param builder RouteLocator构建类
     * @return RouteLocator
     */
    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route
                        ("roue-api-1",
                                v -> v.header("token")
                                        .filters(f -> f.filter((exchange, chain) -> null))
                                        .uri("lb://customer-gateway")
                        ).build();
    }

}
